package backed.service.impl;

import backed.config.CosConfig;
import backed.service.FileUploadService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    
    @Autowired
    private COSClient cosClient;
    
    @Override
    public String uploadFile(MultipartFile file, Long userId) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        
        // 获取文件扩展名
        String extension = "";
        int dotIndex = originalFilename.lastIndexOf(".");
        if (dotIndex > 0) {
            extension = originalFilename.substring(dotIndex);
        }
        
        // 获取当前日期（格式：yyyy-MM-dd）
        String currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        
        // 生成唯一文件名: 时间戳_UUID.扩展名
        String fileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString().replace("-", "") + extension;
        
        // 构建文件存储路径：natural_intelligence_link/用户ID/日期/文件名
        String filePath = "natural_intelligence_link/" + userId + "/" + currentDate + "/" + fileName;
        
        // 设置对象元数据
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentType(file.getContentType());
        
        // 上传文件
        try (InputStream inputStream = file.getInputStream()) {
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                CosConfig.BUCKET, 
                filePath,  // 使用带目录的完整路径
                inputStream, 
                metadata
            );
            // 设置文件为公开可读，确保Coze API可以访问
            putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
            cosClient.putObject(putObjectRequest);
        }
        
        // 返回文件访问URL
        return CosConfig.DOMAIN + "/" + filePath;
    }
    
    @Override
    public void deleteFile(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return;
        }
        
        try {
            // 从URL中提取文件key
            String key = fileUrl.replace(CosConfig.DOMAIN + "/", "");
            cosClient.deleteObject(CosConfig.BUCKET, key);
        } catch (Exception e) {
            throw new RuntimeException("删除文件失败: " + e.getMessage(), e);
        }
    }
}
